import React, { useState, useRef } from 'react';
import { motion } from 'framer-motion';
import { useAuth } from '../contexts/AuthContext';
import { createDesign, getDesignStatus, CreateDesignTaskResponse } from '../services/design';
import seaImage from '../images/sea.png';
import tribalImage from '../images/Tribal.png';
import Professional from '../images/Professional.png';
import Bohemian from '../images/Bohemian.jpg';
import Minimalist from '../images/Minimalist.jpg';
import Industrial from '../images/Industrial.jpg';
import Cyberpunk from '../images/Cyberpunk.jpg';
import Scandinavian from '../images/Scandinavian.jpg';

interface CreateDesignProps {
  onDesignCreated?: (imageUrl: string) => void;
  onCreditsUpdated?: () => void;
}

const CreateDesign: React.FC<CreateDesignProps> = ({ onDesignCreated, onCreditsUpdated }) => {
  const { user, isAuthenticated } = useAuth();
  const [selectedImage, setSelectedImage] = useState<string | null>(null);
  const [processedImage, setProcessedImage] = useState<string | null>(null);
  const [selectedStyle, setSelectedStyle] = useState<string>('modern');
  const [selectedRoomType, setSelectedRoomType] = useState<string>('living-room');
  const [isProcessing, setIsProcessing] = useState(false);
  const [currentPollInterval, setCurrentPollInterval] = useState<NodeJS.Timeout | null>(null);
  const [uploadProgress, setUploadProgress] = useState<number>(0);
  const [error, setError] = useState<string | null>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);
  const [success, setSuccess] = useState<boolean>(false);

  const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
    const file = event.target.files?.[0];
    if (file) {
      // Validate file type
      if (!file.type.match('image.*')) {
        setError('Please select an image file');
        return;
      }

      // Validate file size (10MB limit)
      if (file.size > 10 * 1024 * 1024) {
        setError('File size should be less than 10MB');
        return;
      }

      setError(null);
      const reader = new FileReader();
      reader.onloadstart = () => {
        setUploadProgress(0);
      };
      reader.onprogress = (event) => {
        if (event.lengthComputable) {
          const progress = (event.loaded / event.total) * 100;
          setUploadProgress(progress);
        }
      };
      reader.onloadend = () => {
        setUploadProgress(100);
        setSelectedImage(reader.result as string);
        setProcessedImage(null); // Reset processed image when new image is uploaded
      };
      reader.readAsDataURL(file);
    }
  };

  const handleDragOver = (event: React.DragEvent) => {
    event.preventDefault();
    event.stopPropagation();
  };

  const handleDrop = (event: React.DragEvent) => {
    event.preventDefault();
    event.stopPropagation();
    
    const file = event.dataTransfer.files[0];
    if (file) {
      if (!file.type.match('image.*')) {
        setError('Please drop an image file');
        return;
      }

      if (file.size > 10 * 1024 * 1024) {
        setError('File size should be less than 10MB');
        return;
      }

      setError(null);
      const reader = new FileReader();
      reader.onloadstart = () => {
        setUploadProgress(0);
      };
      reader.onprogress = (event) => {
        if (event.lengthComputable) {
          const progress = (event.loaded / event.total) * 100;
          setUploadProgress(progress);
        }
      };
      reader.onloadend = () => {
        setUploadProgress(100);
        setSelectedImage(reader.result as string);
        setProcessedImage(null);
      };
      reader.readAsDataURL(file);
    }
  };

  const handleGenerate = async () => {
    if (!selectedImage || !isAuthenticated) {
      setError('Please log in and upload an image first');
      return;
    }

    setIsProcessing(true);
    setError(null);
    
    try {
      // Convert base64 image to File object
      const base64Data = selectedImage.split(',')[1];
      const mimeType = selectedImage.split(',')[0].split(':')[1].split(';')[0];
      const byteCharacters = atob(base64Data);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const file = new File([byteArray], 'room-image.jpg', { type: mimeType });

      const prompt = `Design ${selectedRoomType} in ${selectedStyle} style`;
      
      // Create design task
      console.log('Creating design with:', {
        roomType: selectedRoomType,
        designStyle: selectedStyle,
        prompt: prompt,
        fileSize: file.size,
        fileType: file.type
      });
      

      
      const response = await createDesign({
        roomType: selectedRoomType,
        designStyle: selectedStyle,
        prompt: prompt,
        file: file
      });
      
      console.log('Create design response:', response);

      if (response.success && response.data.id) {
        // Task created successfully, now poll for completion
        const taskId = response.data.id;
        
        // Update credits immediately if provided
        if (response.data.creditsUsed && onCreditsUpdated) {
          onCreditsUpdated();
        }
        
        // Poll for task completion
          const pollInterval = setInterval(async () => {
            try {
              console.log('Polling status for task:', taskId);
              const statusData = await getDesignStatus(taskId);
              console.log('Status response:', statusData);
              
              if (statusData.success) {
                if (statusData.data.status === 'completed' && statusData.data.generatedImageUrl) {
                  console.log('Task completed successfully');
                  console.log('Generated image URL:', statusData.data.generatedImageUrl);
                  // 添加更多调试信息
                  clearInterval(pollInterval);
                  setCurrentPollInterval(null);
                  setProcessedImage(statusData.data.generatedImageUrl);
                  setIsProcessing(false);
                  setSuccess(true); // 设置成功状态
                  // Notify parent components
                  if (onDesignCreated) {
                    onDesignCreated(statusData.data.generatedImageUrl);
                  }
                } else if (statusData.data.status === 'failed') {
                  console.log('Task failed:', statusData.data.errorMessage);
                  clearInterval(pollInterval);
                  setCurrentPollInterval(null);
                  setIsProcessing(false);
                  setError(statusData.data.errorMessage || 'Design generation failed');
                } else {
                  console.log('Task still in progress, status:', statusData.data.status);
                }
                // If status is still 'pending' or 'processing', continue polling
              } else {
                console.error('Status check failed:', statusData.message);
                // 添加错误提示
                setError('无法获取任务状态: ' + (statusData.message || '未知错误'));
              }
            } catch (pollError) {
              const error = pollError as any;
              console.error('Error polling task status:', error);
              console.error('Poll error details:', {
                message: error.message,
                response: error.response?.data,
                status: error.response?.status
              });
              // 添加网络错误提示
              if (error.response?.status === 404) {
                setError('后端服务未找到，请检查API服务是否正常运行');
                clearInterval(pollInterval);
                setCurrentPollInterval(null);
                setIsProcessing(false);
              } else if (error.code === 'NETWORK_ERROR' || !error.response) {
                setError('网络连接错误，请检查后端服务是否启动');
                clearInterval(pollInterval);
                setCurrentPollInterval(null);
                setIsProcessing(false);
              }
              // Continue polling on other errors, don't break the loop
            }
          }, 3000); // Poll every 3 seconds
          
          // Store the interval reference
          setCurrentPollInterval(pollInterval);
        
        // Set a timeout to stop polling after 5 minutes
        setTimeout(() => {
          clearInterval(pollInterval);
          setCurrentPollInterval(null);
          if (isProcessing) {
            setIsProcessing(false);
            setError('Design generation timed out. Please try again.');
          }
        }, 300000); // 5 minutes timeout
        
      } else {
        throw new Error(response.message || 'Failed to create design task');
      }
      
    } catch (error: any) {
      console.error('Error processing image:', error);
      console.error('Error details:', {
        message: error.message,
        response: error.response?.data,
        status: error.response?.status
      });
      
      let errorMessage = 'Failed to process image. Please try again.';
      if (error.response?.data?.message) {
        errorMessage = error.response.data.message;
      } else if (error.message) {
        errorMessage = error.message;
      }
      
      setError(errorMessage);
      setIsProcessing(false);
    }
  };

  const roomTypes = [
    { id: 'living-room', name: 'Living Room' },
    { id: 'bedroom', name: 'Bedroom' },
    { id: 'kitchen', name: 'Kitchen' },
    { id: 'bathroom', name: 'Bathroom' },
    { id: 'office', name: 'Office' },
    { id: 'dining-room', name: 'Dining Room' },
    { id: 'game-room', name: 'Game Room' },
    { id: 'basement', name: 'Basement' },
    { id: 'outdoor-terrace', name: 'Outdoor Terrace' },
  ];

  const designStyles = [
    { id: 'modern', name: 'Modern', image: 'https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80' },
    { id: 'minimalist', name: 'Minimalist', image: Minimalist },
    { id: 'scandinavian', name: 'Scandinavian', image: Scandinavian },
    { id: 'industrial', name: 'Industrial', image: Industrial },
    { id: 'bohemian', name: 'Bohemian', image: Bohemian },
    { id: 'tribal', name: 'Tribal', image: tribalImage },
    { id: 'cyberpunk', name: 'Cyberpunk', image: Cyberpunk },
    { id: 'coastal', name: 'Coastal', image: seaImage },
    { id: 'professional', name: 'Professional', image: Professional },
  ];

  if (!isAuthenticated) {
    return (
      <div className="bg-white rounded-xl shadow-sm border border-gray-200 p-6 md:p-8">
        <div className="text-center py-8">
          <svg className="mx-auto h-12 w-12 text-gray-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
          </svg>
          <h3 className="mt-2 text-sm font-medium text-gray-900">Authentication Required</h3>
          <p className="mt-1 text-sm text-gray-500">Please log in to create designs</p>
        </div>
      </div>
    );
  }

  return (
    <motion.div
      initial={{ opacity: 0, y: 20 }}
      animate={{ opacity: 1, y: 0 }}
      transition={{ duration: 0.3 }}
      className="space-y-6"
    >
      <div className="bg-white rounded-2xl shadow-2xl border border-gray-100 p-6 md:p-8">
        <div className="flex flex-col sm:flex-row sm:items-center sm:justify-between mb-6">
          <h2 className="text-2xl font-bold text-gray-900 mb-4 sm:mb-0">Create New Design</h2>
          <button
            onClick={() => {
              setSelectedImage(null);
              setProcessedImage(null);
              setError(null);
              setUploadProgress(0);
            }}
            className="inline-flex items-center px-4 py-2 border border-gray-300 rounded-lg shadow-sm text-sm font-medium text-gray-700 bg-white hover:bg-blue-50 hover:border-blue-400 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-400 transition-all"
          >
            <svg className="w-4 h-4 mr-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15" />
            </svg>
            Reset
          </button>
        </div>
        {/* Error Display */}
        {error && (
          <div className="bg-red-50 border border-red-200 rounded-lg p-4 mb-6">
            <div className="flex items-center">
              <svg className="w-5 h-5 text-red-400 mr-2" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
              </svg>
              <p className="text-red-800">{error}</p>
            </div>
          </div>
        )}
        <div className="w-full">
          <div className="space-y-6 w-full">
            {/* Image Upload Section */}
            <div>
              <label className="block text-lg font-medium text-gray-700 mb-2">
                Upload Your Room Photo
              </label>
              <div 
                className="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-dashed rounded-2xl cursor-pointer bg-gradient-to-br from-blue-50 via-purple-50 to-white hover:shadow-[0_0_24px_4px_#a5b4fc] hover:border-blue-400 border-blue-200 transition-all duration-200"
                onClick={() => fileInputRef.current?.click()}
                onDragOver={handleDragOver}
                onDrop={handleDrop}
              >
                <div className="space-y-1 text-center">
                  {selectedImage ? (
                    <div className="relative">
                      <img
                        src={selectedImage}
                        alt="Uploaded room"
                        className="max-h-64 w-auto mx-auto rounded-xl shadow-lg"
                      />
                      <button
                        onClick={(e) => {
                          e.stopPropagation();
                          setSelectedImage(null);
                          setProcessedImage(null);
                        }}
                        className="absolute top-2 right-2 bg-red-500 text-white p-2 rounded-full hover:bg-red-600 shadow-lg transition-colors"
                      >
                        <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                        </svg>
                      </button>
                    </div>
                  ) : (
                    <>
                      <svg
                        className="mx-auto h-16 w-16 text-blue-300 rounded-full bg-blue-50 p-2 shadow-md"
                        stroke="currentColor"
                        fill="none"
                        viewBox="0 0 48 48"
                      >
                        <path
                          d="M28 8H12a4 4 0 00-4 4v20m32-12v8m0 0v8a4 4 0 01-4 4H12a4 4 0 01-4-4v-4m32-4l-3.172-3.172a4 4 0 00-5.656 0L28 28M8 32l9.172-9.172a4 4 0 015.656 0L28 28m0 0l4 4m4-24h8m-4-4v8m-12 4h.02"
                          strokeWidth={2}
                          strokeLinecap="round"
                          strokeLinejoin="round"
                        />
                      </svg>
                      <div className="flex text-sm text-gray-600 justify-center">
                        <span className="relative cursor-pointer bg-white rounded-md font-medium text-blue-600 hover:text-blue-500 transition-all">Upload a file</span>
                        <p className="pl-1">or drag and drop</p>
                      </div>
                      <p className="text-xs text-gray-500">PNG, JPG, GIF up to 10MB</p>
                    </>
                  )}
                  {uploadProgress > 0 && uploadProgress < 100 && (
                    <div className="w-full bg-gray-200 rounded-full h-2.5 mt-2">
                      <div
                        className="bg-gradient-to-r from-blue-400 to-purple-400 h-2.5 rounded-full transition-all duration-300"
                        style={{ width: `${uploadProgress}%` }}
                      ></div>
                    </div>
                  )}
                </div>
              </div>
              <input
                ref={fileInputRef}
                type="file"
                className="hidden"
                accept="image/*"
                onChange={handleImageUpload}
              />
            </div>
            {/* Room Type Selection */}
            <div>
              <label className="block text-lg font-medium text-gray-700 mb-4">
                Select Room Type
              </label>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-3">
                {roomTypes.map((room) => (
                  <button
                    key={room.id}
                    onClick={() => setSelectedRoomType(room.id)}
                    className={`py-2 px-4 rounded-xl text-sm font-medium transition-all duration-200 shadow-sm border-2 focus:outline-none focus:ring-2 focus:ring-blue-300
                      ${selectedRoomType === room.id
                        ? 'bg-gradient-to-r from-blue-400 to-purple-400 text-white border-blue-400 shadow-lg scale-105'
                        : 'bg-gray-50 text-gray-700 border-gray-200 hover:bg-blue-50 hover:border-blue-300 hover:scale-105'}
                    `}
                  >
                    {room.name}
                  </button>
                ))}
              </div>
            </div>
            {/* Style Selection */}
            <div>
              <label className="block text-lg font-medium text-gray-700 mb-4">
                Choose Design Style
              </label>
              <div className="grid grid-cols-2 md:grid-cols-3 gap-4">
                {designStyles.map((style) => (
                  <button
                    key={style.id}
                    onClick={() => setSelectedStyle(style.id)}
                    className={`relative rounded-xl overflow-hidden group shadow-md transition-all duration-200
                      ${selectedStyle === style.id ? 'ring-2 ring-blue-400 scale-105 shadow-xl' : 'hover:scale-105 hover:shadow-lg'}
                    `}
                  >
                    <img
                      src={style.image}
                      alt={style.name}
                      className="w-full h-24 object-cover transition-transform duration-300 group-hover:scale-105"
                    />
                    <div className="absolute inset-0 bg-black bg-opacity-40 flex items-center justify-center">
                      <span className="text-white font-semibold text-base drop-shadow-lg">{style.name}</span>
                    </div>
                  </button>
                ))}
              </div>
            </div>
            {/* Generate Button */}
            <div>
              {!isProcessing ? (
                <button
                  onClick={handleGenerate}
                  disabled={!selectedImage}
                  className={`w-full py-3 px-4 rounded-xl text-white font-semibold text-lg shadow-lg transition-all duration-200
                    ${!selectedImage
                      ? 'bg-gray-300 cursor-not-allowed'
                      : 'bg-gradient-to-r from-blue-500 to-purple-500 hover:scale-105 hover:shadow-[0_0_24px_6px_#a5b4fc]'}                  
                  `}
                >
                  {processedImage ? 'Regenerate Design' : 'Generate Design'} <span className="ml-2 text-sm opacity-80">(Cost: 1 credit)</span>
                </button>
              ) : (
                <div className="flex items-center justify-center py-2 bg-gray-100 rounded-lg">
                  <svg className="animate-spin -ml-1 mr-3 h-5 w-5 text-blue-500" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                    <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                    <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                  </svg>
                  <span className="text-gray-700">Generating design, please wait...</span>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>
    </motion.div>
  );
};

export default CreateDesign;